package com.china08.yxyapi.api.home.activity.healthcompetition.huodongtongji;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionStudent;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.huodong.YxyCompetitionStudentRepository;

/**
 * 健康知识竞赛 年级 班级 参与人数 参与率 平均分
 * 
 * @author zd.Jin
 *
 *
 */
@CrossOrigin
@RestController
public class HealthCompetionTongjiByClassController extends YxyApiBaseController {
	@Value("${yx.rest.api.yx.path}")
	private String yxpath;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private YxyCompetitionStudentRepository yxyCompetitionStudentRepository;

	@RequestMapping(value = "/api_yw/home/activity/healthcompetition/huodongtongji/classtongji", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public RespModel process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
		RespModel respModel = new RespModel();
		String school = reqModel.schoolId;
		String gradeCode = reqModel.gradeCode;
		String gradeName = reqModel.gradeName;
		String classId = reqModel.classId;
		DecimalFormat df = new DecimalFormat("######0.00");
		if ("all".equals(classId)) {
			// 得到参与人数总数
			List<YxyCompetitionStudent> list = yxyCompetitionStudentRepository.findByStatusAndSchoolIdAndGrade(2,
					school, gradeName);
			respModel.total = list.size();
			// 计算该学校下参与学生平均分
			TypedAggregation<YxyCompetitionStudent> totalavg = Aggregation.newAggregation(YxyCompetitionStudent.class,
					Aggregation.match(
							Criteria.where("status").is(2).and("schoolId").is(school).and("grade").is(gradeName)),
					Aggregation.group("grade").avg("score").as("avg"));
			AggregationResults<DateModel> resultZongtotal = mongoTemplate.aggregate(totalavg, DateModel.class);
			List<DateModel> dateModelLsttotal = resultZongtotal.getMappedResults();
			if (dateModelLsttotal.size() > 0) {
				respModel.avg = Double.valueOf(df.format(dateModelLsttotal.get(0).avg));
			}
			// 计算参与率
			try {
				HttpHeaders headers = new HttpHeaders();
				MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
				headers.setContentType(type);
				headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
				Map<String, Object> formMap = new HashMap<String, Object>();
				formMap.put("grade", gradeCode);
				formMap.put("schoolId", reqModel.schoolId);
				HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
				SchRespModel httpResult = restTemplate.postForObject(yxpath + "/comm/stucount/schandgrade/studentcount",
						formEntity, SchRespModel.class);
				Integer studentcount = httpResult.stucount;
				Double rate = 0.0d;
				if (studentcount != 0) {
					Double aLong = (double) list.size() / studentcount;
					rate = Double.valueOf(df.format(aLong * 100));
				}
				respModel.rate = rate;

			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// 得到参与人数总数
			List<YxyCompetitionStudent> list = yxyCompetitionStudentRepository
					.findByStatusAndSchoolIdAndGradeAndClassId(2, school, gradeName, classId);
			respModel.total = list.size();
			// 计算该学校下参与学生平均分
			TypedAggregation<YxyCompetitionStudent> totalavg = Aggregation.newAggregation(YxyCompetitionStudent.class,
					Aggregation.match(Criteria.where("status").is(2).and("schoolId").is(school).and("grade")
							.is(gradeName).and("classId").is(classId)),
					Aggregation.group("classId").avg("score").as("avg"));
			AggregationResults<DateModel> resultZongtotal = mongoTemplate.aggregate(totalavg, DateModel.class);
			List<DateModel> dateModelLsttotal = resultZongtotal.getMappedResults();
			if (dateModelLsttotal.size() > 0) {
				respModel.avg = Double.valueOf(df.format(dateModelLsttotal.get(0).avg));
			}
			// 计算参与率
			try {
				HttpHeaders headers = new HttpHeaders();
				MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
				headers.setContentType(type);
				headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
				Map<String, Object> formMap = new HashMap<String, Object>();
				formMap.put("classId", classId);
				HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
				SchRespModel httpResult = restTemplate.postForObject(
						yxpath + "/comm/stucount/schandgradeandclassid/studentcount", formEntity, SchRespModel.class);
				Integer studentcount = httpResult.stucount;
				Double rate = 0.0d;
				if (studentcount != 0) {
					Double aLong = (double) list.size() / studentcount;
					rate = Double.valueOf(df.format(aLong * 100));
				}
				respModel.rate = rate;

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return respModel;
	}

	// 远程调用接口,查询学校下小学初中高中共有多少学生
	protected static class SchRespModel extends YxyApiReqModel {
		// 学生总数
		public Integer stucount;
	}

	class DateModel {
		public Double avg;
	}

	protected static class ReqModel extends YxyApiReqModel {
		// 学校id
		public String schoolId;
		// 所在年级名称
		public String gradeCode;
		// 所在年级名称
		public String gradeName;
		// 所在班级id(全部传"all")
		public String classId;

		@Override
		public void autoCheck() {
			Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "请填写学校ID");
			Assert.notNull(StringUtils.defaultIfBlank(gradeCode, null), "请填写年级code");
			Assert.notNull(StringUtils.defaultIfBlank(gradeName, null), "请填写年级名称");
			Assert.notNull(StringUtils.defaultIfBlank(classId, null), "请填写班级ID");
		}
	}

	protected static class RespModel extends YxyApiRespModel {
		// 总参与人数
		public Integer total;
		// 参与率
		public Double rate;
		// 平均分
		public Double avg;
	}
}
